package org.example.mq.consumer;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.example.AppContext;
import org.springframework.stereotype.Component;

/**
 * @Name ：AbstractMQConsumer
 * @Description ：抽象类mq消费
 * @Author ：liuyubo
 * @Date ：2024/3/27 10:24
 * @Version ：1.0.0
 * @History ：
 */
@Component
@Slf4j
public abstract class AbstractMQConsumer implements MessageListenerConsumer {

    protected String gid;

    @Override
    public String getGid() {
        return gid;
    }

    @Override
    public void setGid(String gid) {
        this.gid = gid;
    }


    @Override
    public Action consume(Message message, ConsumeContext context) {
        if (StringUtils.isNotBlank(message.getUserProperties().getProperty("routeVersion"))) {
            AppContext.setThreadLocal("routeVersion",
                    message.getUserProperties().getProperty("routeVersion"));
        }
        Long mqLogId = null;
        try {
            log.info("初始化 mqLog 信息 mqLog：{}", message);
            return handler(message, context, mqLogId);
        } catch (Exception e) {
            log.info("初始化 mqLog 信息 发生异常 message：{}，Exception：{}",
                    JSONObject.toJSONString(message), e.getMessage());
            return null;
        } finally {
            AppContext.clearThreadLocal();
        }
    }

    protected abstract Action handler(Message message, ConsumeContext context, Long mqLogId);

}
